import { HttpClient, HttpParams } from '@angular/common/http';
import { Inject, Injectable, Injector } from '@angular/core';
import { observable, Observable } from 'rxjs';
import { API_CONFIG, ServicesModule } from './services.module';
import { map } from 'rxjs/internal/operators';
import { Lyric, Song, SongUrl } from './data-types/common.types';

@Injectable({
  providedIn: ServicesModule
})
export class SongService {

  constructor(private http:HttpClient, @Inject(API_CONFIG) private uri:string ) { }


  // 获取歌曲地址
  getSongUrl(ids:string): Observable<SongUrl[]>{
    const params = new HttpParams().set("id",ids)
    return this.http.get(this.uri + 'song/url',{params})
    .pipe(map((res:any)=>res.data));
  }

  getSongList(songs:Song | Song[]):Observable<Song[]>{
    const songArr = Array.isArray(songs) ? songs.slice():[songs]
    const ids = songArr.map(item=>item.id).join(',')
    return this.getSongUrl(ids).pipe(map(urls=>this.generateSongList(songArr,urls)))
  }

  private generateSongList(songs:Song[],urls:SongUrl[]):Song[]{
    const result:Song[] = []
    songs.forEach(song=>{
      const url = urls.find(url=>url.id === song.id)?.url;
      if(url){
        result.push({...song,url})
      }
    })
    return result
  }

  // 获取歌曲详情
  getSongDetail(ids: string): Observable<Song>{
    const params = new HttpParams().set("ids", ids)
    return this.http.get(this.uri + 'song/detail',{ params })
    .pipe(map((res:any) => res.songs[0]));
  }

  // 获取歌词
  getLyric(id: number): Observable<Lyric>{
    const params = new HttpParams().set("id",id.toString());
    return this.http.get(this.uri + 'lyric',{params})
    .pipe(map((res:any) => {
      return {
        lyric: res.lrc?.lyric || '',
        tlyric: res.tlyric?.lyric || '',
      }
    }));
  }
}
